<?php
declare(strict_types=1);

namespace App\Common\Modular\User\Serve;

use App\Common\Modular\User\Model\UserModel;
use Core\Basics\BasicsServe;
use Zms\Exception\AppException;

/**
 * 用户
 * @method UserModel getModel()
 */
class UserServe extends BasicsServe
{

    public static function model(): string
    {
        return UserModel::class;
    }


    /**
     * @describe 检测手机号是否占用
     * @user zlf <zms-pro@qq.com> 2025/3/11
     * @param string $mobile
     * @param int|null $id
     * @return bool
     */
    public function isPhoneOccupied(string $mobile, ?int $id = null): bool
    {
        $query = $this->search(['mobile' => $mobile]);
        if ($id) {
            $query->where('id', '!=', $id);
        }
        return $query->exists();
    }


    /**
     * @describe 设置会员信息
     * @user zlf <zms-pro@qq.com> 2025/3/11
     * @param array $data
     * @return ?UserModel
     * @throws AppException
     */
    public function saveUserData(array $data): ?UserModel
    {

        $id = $data['id'] ?? 0;
        unset($data['id']);

        /**
         * 获取用户模型
         * @var UserModel $user
         */
        $user = $id ? $this->search(['id' => $id])->first() : $this->getModel();
        if (!$user) {
            throw new AppException("编辑失败,会员信息已失效");
        }
        if (isset($data['mobile']) && $data['mobile']) {
            if ($this->isPhoneOccupied($data['mobile'], $user->id)) {
                throw new AppException('手机号已绑定其他账号');
            }
        }
        $user->setAttributes($data);

        return $user->save() ? $user : null;
    }
}